#include "DefineBitsEditor.h"
#include "ui_DefineBitsEditor.h"
#include <QPainter>
#include <QGraphicsPixmapItem>
#include <QFileDialog>
#include "swf/SWFTagWrapper.h"
#include "swf/utils/ImageHelper.h"

DefineBitsEditor::DefineBitsEditor(SWFTagWrapper* tag, QWidget *parent)
	: QWidget(parent)
	, ui(new Ui::DefineBitsEditor)
	, _wrapper(tag)
{
	_bits = dynamic_cast<TagDefineBits*>(_wrapper->getTag());
	assert(_bits);

    ui->setupUi(this);

	_image = ImageHelper::convertDefineBitsToImage(_bits);
	
	QGraphicsScene *scene = new QGraphicsScene(this);
	_graphicsPixmapItem = new QGraphicsPixmapItem();
	_graphicsPixmapItem->setPixmap(QPixmap::fromImage(*_image));
	scene->addItem(_graphicsPixmapItem);
	_graphicsPixmapItem->setPos(0,0);
	ui->graphicsView->setScene(scene);
}

DefineBitsEditor::~DefineBitsEditor()
{
    delete ui;
	if (_image)
		delete _image;
}

void DefineBitsEditor::onReplace()
{
	QString file = QFileDialog::getOpenFileName(this, "Select Picture", QString());
	QFile f(file);
	if (f.exists())
	{
		QImage img(file);

		_bits = ImageHelper::createDefineBits(&img, true);
		_wrapper->replace(_bits);

		_graphicsPixmapItem->setPixmap(QPixmap::fromImage(img));
	}
}

void DefineBitsEditor::onExport()
{
	if (_image != nullptr)
	{
		QString filePath = QFileDialog::getSaveFileName(this, "Save Image", QString(), "Image(*.jpeg,*.png)");
		_image->save(filePath);
	}
}

const QString DefineBitsEditor::getEditorName() const 
{
	return QString("Image %1").arg(_bits->characterID);
}

QWidget* DefineBitsEditor::asWidget() const 
{
	return (QWidget*) this;
}